//
//  WMEClubHeadView.m
//  everyDay_duiTang
//
//  Created by 恩叔 on 16/2/26.
//  Copyright © 2016年 enshu. All rights reserved.
//

#import "WMEClubHeadView.h"
#import <Masonry.h>
#import <AFNetworking.h>
#import "WMEClubNewsViewController.h"
#import <UIImageView+WebCache.h>

#pragma mark - 点击club的详情的头部视图
@interface WMEClubHeadView ()
@property (nonatomic, retain)UILabel *from;/**<来自哪儿的label*/
@property (nonatomic, retain)UILabel *type;/**<俱乐部类型*/
@property (nonatomic, retain)UILabel *content;/**<内容*/
@property (nonatomic, retain)UILabel *senderName;/**<用户名*/
@property (nonatomic, retain)UILabel *addDatetime;/**<添加的时间,发布的时间*/
@property (nonatomic, retain)UILabel *visitCount;/**<查看的人数*/

@property (nonatomic, retain)UIView *bgView;/**<背景视图*/

@property (nonatomic, retain)UILabel *line1;/**<美观线*/
@property (nonatomic, retain)UILabel *line2;/**<美观线*/
@property (nonatomic, retain)UILabel *wenben;/**<文本*/

@property (nonatomic, retain)UIImageView *path;/**<图片*/
@property (nonatomic, retain)UIScrollView *scrollView;
@property (nonatomic, assign)CGRect originalFrame;
@property (nonatomic, retain)UIImageView *lastImageView;
@end

@implementation WMEClubHeadView

-(void)dealloc
{
    [_from release];
    [_type release];
    [_content release];
    [_senderName release];
    [_addDatetime release];
    [_visitCount release];
    [_bgView release];
    [_line1 release];
    [_line2 release];
    [_wenben release];
    [_path release];
    [_scrollView release];
    [_lastImageView release];
    [super dealloc];
}
#pragma mark -初始化
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        //打开用户交互
        self.userInteractionEnabled = YES;
        self.backgroundColor = [UIColor colorWithRed:244/255.0 green:244/255.0 blue:244/255.0 alpha:1];
        
        //来着那个俱乐部
        self.from = [[UILabel alloc] init];
//        _from.backgroundColor = [UIColor redColor];
        _from.font = [UIFont systemFontOfSize:9];
        _from.textColor = [UIColor lightGrayColor];
        _from.userInteractionEnabled = YES;
        UITapGestureRecognizer *fromTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fromTapAction:)];
        [_from addGestureRecognizer:fromTap];
        [self addSubview:_from];
        [_from release];
        
        //背景视图
        self.bgView = [[UIView alloc] init];
        _bgView.backgroundColor = [UIColor whiteColor];
        _bgView.userInteractionEnabled = YES;
        [self addSubview:_bgView];
        [_bgView release];
        
        //俱乐部类型
        self.type = [[UILabel alloc] init];
        _type.backgroundColor = [UIColor colorWithRed:160/255.0 green:160/255.0 blue:233/255.0 alpha:1];
        _type.textColor = [UIColor colorWithRed:0 green:160/255.0 blue:233/255.0 alpha:1];
        _type.font = [UIFont systemFontOfSize:11];
        _type.textAlignment = NSTextAlignmentCenter;
        [self.bgView addSubview:_type];
        [_type release];
        
        //内容
        self.content = [[UILabel alloc] init];
//        _content.backgroundColor = [UIColor yellowColor];
        _content.font = [UIFont systemFontOfSize:13];
        _content.numberOfLines = 0;
        [self.bgView addSubview:_content];
        [_content release];
        
        //用户名
        self.senderName = [[UILabel alloc] init];
//        _senderName.backgroundColor = [UIColor greenColor];
        _senderName.textColor = [UIColor colorWithRed:0 green:160/255.0 blue:233/255.0 alpha:1];
        //打开交互
        _senderName.userInteractionEnabled = YES;
        UITapGestureRecognizer *nameTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(nameTapAction:)];
        [_senderName addGestureRecognizer:nameTap];
        _senderName.font = [UIFont systemFontOfSize:12];
        [self.bgView addSubview:_senderName];
        [_senderName release];
        [nameTap release];
        
        //发布时间
        self.addDatetime = [[UILabel alloc] init];
//        _addDatetime.backgroundColor = [UIColor blueColor];
        _addDatetime.textColor = [UIColor lightGrayColor];
        _addDatetime.font = [UIFont systemFontOfSize:10];
        [self.bgView addSubview:_addDatetime];
        [_addDatetime release];
        
        //查看的人数 (访问的人数)
        self.visitCount = [[UILabel alloc] init];
//        _visitCount.backgroundColor = [UIColor cyanColor];
        _visitCount.textAlignment = NSTextAlignmentRight;
        _visitCount.textColor = [UIColor lightGrayColor];
        _visitCount.font = [UIFont systemFontOfSize:11];
        [self.bgView addSubview:_visitCount];
        [_visitCount release];
        
        //美观的线
        self.line1 = [[UILabel alloc] init];
        _line1.backgroundColor = [UIColor lightGrayColor];
        [self addSubview:_line1];
        [_line1 release];
        
        //美观的线
        self.line2 = [[UILabel alloc] init];
        _line2.backgroundColor = [UIColor lightGrayColor];
        [self addSubview:_line2];
        [_line2 release];
        
        //放置热门评论的
        self.wenben = [[UILabel alloc] init];
        _wenben.font = [UIFont systemFontOfSize:13];
        _wenben.textColor = [UIColor lightGrayColor];
//        _wenben.backgroundColor = [UIColor redColor];
        _wenben.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_wenben];
        [_wenben release];
        
        //图片
        self.path = [[UIImageView alloc] init];
        _path.contentMode = UIViewContentModeScaleAspectFill;
        _path.clipsToBounds = YES;
        _path.userInteractionEnabled = YES;
        UITapGestureRecognizer *pathTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pathTapAction:)];
        [self.path addGestureRecognizer:pathTap];
        [self.bgView addSubview:_path];
        [_path release];
    }
    return self;
}
#pragma mark -重写setting方法
- (void)setDic:(NSDictionary *)dic
{
    if (_dic != dic) {
        [_dic release];
        _dic = [dic retain];
        
        _from.text = [NSString stringWithFormat:@"来自 %@ 更多话题" , _dic[@"club"][@"name"]];
        
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"来自 %@ 更多话题" , _dic[@"club"][@"name"]]];

        NSInteger i = [_dic[@"club"][@"name"] length];
        [str addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:10] range:NSMakeRange(3, i)];
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(3, i)];
        _from.attributedText = str;

        _type.text = _dic[@"tags"][0][@"name"];
        
        _content.text = _dic[@"content"];
        
        _senderName.text = _dic[@"sender"][@"username"];
        
        _addDatetime.text = [[self class] compareCurrentTime:_dic[@"add_datetime_ts"]];
        
        _visitCount.text = [NSString stringWithFormat:@"浏览%@", _dic[@"visit_count"]];
        
        _wenben.text = @"热门评论";
        if (_dic[@"photos"]) {
            [_path sd_setImageWithURL:[NSURL URLWithString:_dic[@"photos"][0][@"path"]]];
        }
    }
}

#pragma mark -布局函数
- (void)layoutSubviews
{
    [super layoutSubviews];
    __block __typeof(&*self)bs = self;
    [_from mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bs.mas_left).with.offset(10);
        make.right.equalTo(bs.mas_right).with.offset(-10);
        make.top.equalTo(bs.mas_top).with.offset(0);
        make.height.equalTo(@30);
    }];
    
    CGFloat contentHeight = [[self class] heightWithText:_dic[@"content"] FontOfSize:13];
    if (![_dic[@"tags"][0][@"name"] length]) {
        if (![_dic[@"photos"][0][@"path"] length]) {
            _bgView.frame = CGRectMake(0, 30, WIDTH, contentHeight + 48);
        }else {
            _bgView.frame = CGRectMake(0, 30, WIDTH, contentHeight + 48 + 90);
        }
    }else{
        if (![_dic[@"photos"][0][@"path"] length]) {
            _bgView.frame = CGRectMake(0, 30, WIDTH , contentHeight + 78);
        }else{
            _bgView.frame = CGRectMake(0, 30, WIDTH, contentHeight + 78 + 90);
        }
    }
//    [_bgView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(bs.mas_left).with.offset(0);
//        make.right.equalTo(bs.mas_right).with.offset(0);
//        make.top.equalTo(_from.mas_bottom).with.offset(10);
//        make.height.equalTo(@100);
//    }];
    if (![_dic[@"tags"][0][@"name"] length]) {
        [_type mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_bgView.mas_left).with.offset(10);
            make.top.equalTo(_bgView.mas_top).with.offset(0);
            make.height.equalTo(@0);
            make.width.equalTo(@0);
        }];
    }else{
        [_type mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_bgView.mas_left).with.offset(10);
            make.top.equalTo(_bgView.mas_top).with.offset(10);
            make.height.equalTo(@20);
            make.width.equalTo(@30);
        }];
    }
    _content.frame = CGRectMake(10, _type.frame.origin.y + _type.frame.size.height + 10, WIDTH - 20, contentHeight);
    NSLog(@"$$%lf", _content.frame.size.height);
//    [_content mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo (_bgView.mas_left).with.offset(0);
//        make.
//    }];
    
    if ([_dic[@"photos"][0][@"path"] length]) {
        [_path mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_bgView.mas_left).with.offset(10);
            make.top.equalTo(_content.mas_bottom).with.offset(10);
            make.size.mas_equalTo(CGSizeMake(80, 80));
        }];
        CGFloat nameWidth = [[self class] widthWithText:_dic[@"sender"][@"username"] MySize:CGSizeMake(WIDTH / 2, 15) MyFontSize:12];
        _senderName.frame = CGRectMake(10, _path.frame.size.height  + 10 + _content.frame.origin.y + _content.frame.size.height + 10, nameWidth, 15);
        //    [_senderName mas_makeConstraints:^(MASConstraintMaker *make) {
        //        make.left.equalTo(_bgView.mas_left).with.offset(10);
        //        make.top.equalTo(_content.mas_bottom).with.offset(10);
        //        make.height.equalTo(@15);
        //        make.width.equalTo(@(nameWidth));
        //    }];
        
        [_addDatetime mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_senderName.mas_right).with.offset(10);
            make.top.equalTo(_path.mas_bottom).with.offset(10);
            make.width.equalTo(@100);
            make.height.equalTo(@15);
        }];
        
        
        CGFloat visitWidth = [[self class] widthWithText:[NSString stringWithFormat:@"浏览%@", _dic[@"visit_count"]] MySize:CGSizeMake(WIDTH / 2, 15) MyFontSize:13];
        [_visitCount mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_bgView.mas_right).with.offset(-visitWidth - 10);
            make.top.equalTo(_path.mas_bottom).with.offset(10);
            make.width.equalTo(@(visitWidth));
            make.height.equalTo(@15);
        }];
        
        [_wenben mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(@60);
            make.top.equalTo(_bgView.mas_bottom).with.offset(12.2);
            make.centerX.mas_equalTo(bs.mas_centerX);
        }];
        
        [_line1 mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(bs.mas_left).with.offset(10);
            make.right.equalTo(_wenben.mas_left).with.offset(-10);
            make.top.equalTo(_bgView.mas_bottom).with.offset(20);
            make.height.equalTo(@0.4);
        }];
        
        [_line2 mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_wenben.mas_right).with.offset(10);
            make.right.equalTo(bs.mas_right).with.offset(-10);
            make.top.equalTo(_bgView.mas_bottom).with.offset(20);
            make.height.equalTo(@0.4);
        }];

    }else{
    
        CGFloat nameWidth = [[self class] widthWithText:_dic[@"sender"][@"username"] MySize:CGSizeMake(WIDTH / 2, 15) MyFontSize:12];
        _senderName.frame = CGRectMake(10, _content.frame.origin.y + _content.frame.size.height + 10, nameWidth, 15);
        //    [_senderName mas_makeConstraints:^(MASConstraintMaker *make) {
        //        make.left.equalTo(_bgView.mas_left).with.offset(10);
        //        make.top.equalTo(_content.mas_bottom).with.offset(10);
        //        make.height.equalTo(@15);
        //        make.width.equalTo(@(nameWidth));
        //    }];
        
        [_addDatetime mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_senderName.mas_right).with.offset(10);
            make.top.equalTo(_content.mas_bottom).with.offset(10);
            make.width.equalTo(@100);
            make.height.equalTo(@15);
        }];
        
        
        CGFloat visitWidth = [[self class] widthWithText:[NSString stringWithFormat:@"浏览%@", _dic[@"visit_count"]] MySize:CGSizeMake(WIDTH / 2, 15) MyFontSize:13];
        [_visitCount mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_bgView.mas_right).with.offset(-visitWidth - 10);
            make.top.equalTo(_content.mas_bottom).with.offset(10);
            make.width.equalTo(@(visitWidth));
            make.height.equalTo(@15);
        }];
        
        [_wenben mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(@60);
            make.top.equalTo(_bgView.mas_bottom).with.offset(12.2);
            make.centerX.mas_equalTo(bs.mas_centerX);
        }];
        
        [_line1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(bs.mas_left).with.offset(10);
            make.right.equalTo(_wenben.mas_left).with.offset(-10);
            make.top.equalTo(_bgView.mas_bottom).with.offset(20);
            make.height.equalTo(@0.4);
        }];
        
        [_line2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_wenben.mas_right).with.offset(10);
            make.right.equalTo(bs.mas_right).with.offset(-10);
            make.top.equalTo(_bgView.mas_bottom).with.offset(20);
            make.height.equalTo(@0.4);
        }];
       }
}
#pragma maek - 头部点击事件
- (void)fromTapAction:(UITapGestureRecognizer *)tap
{
    NSString *temp = @"http://203.80.144.212/napi/club/detail/?include_fields=share_links_2%2Ccheck_in%2Cexperience%2Crelated_ad%2Ctop_member_target%2Ctopic_update&platform_version=4.4.4&device_platform=L36h&screen_width=1080&screen_height=1776&__domain=www.duitang.com&app_version=67&club_id=54aa79f8a3101a0f75731ca7&platform_name=Android&locale=zh&app_code=nayutas";
    NSString *url = [temp stringByReplacingOccurrencesOfString:@"club_id=54aa79f8a3101a0f75731ca7" withString:[NSString stringWithFormat:@"club_id=%@", _dic[@"club"][@"id"]]];
    AFHTTPSessionManager *data = [AFHTTPSessionManager manager];
    [data GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = responseObject[@"data"];
        [self.delegate pushClubNewsAction:dic];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        nil;
    }];
}

#pragma mark - 名字点击事件
- (void)nameTapAction:(UITapGestureRecognizer *)tap
{
    NSString *userTemp = @"http://www.duitang.com/napi/people/profile/?__dtac=%257B%2522_r%2522%253A%2520%2522998121%2522%257D&_ts=1452865118.002704&app_code=gandalf&app_version=5.8%20rv%3A149591&device_name=iPhone%205&device_platform=iPhone5%2C2&include_fields=relationship%2Cbind_status%2Cinterests%2Cidentity%2Ccity%2Ccitycode%2Cgender%2Cbirthday%2Crecommend_info%2Cclub_count&locale=zh_CN&platform_name=iPhone%20OS&platform_version=9.2&screen_height=568&screen_width=320&user_id=11200118";
    NSString *userStr = [userTemp stringByReplacingOccurrencesOfString:@"11200118" withString:[_dic[@"sender"][@"id"] stringValue]];
    //    NSLog(@"%@", userStr);
    //AFN网络请求
    AFHTTPSessionManager *userData = [AFHTTPSessionManager manager];
    [userData GET:userStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //        NSLog(@"%@", responseObject);
        NSMutableDictionary *userDic = responseObject[@"data"];
        [self.delegate pushUserAction:[_dic[@"sender"][@"id"] stringValue] MyDic:userDic];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        nil;
    }];
}
#pragma mark - 计算文本高
//计算文本高
+ (CGFloat)heightWithText:(NSString *)text FontOfSize:(CGFloat )fontOfSize
{
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:13]};
    //最大范围
    CGSize size = CGSizeMake(WIDTH - 20, 1000);
    //计算 文本 需的rectangular
    CGRect r = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    //返回文本 的 高
    return r.size.height;
}

#pragma mark - 计算文本的宽
//计算文本宽
+ (CGFloat)widthWithText:(NSString *)text MySize:(CGSize)size MyFontSize:(CGFloat)fontSize
{
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]};
    //    CGSize size = CGSizeMake(WIDTH - 100, 10);
    CGRect r = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return r.size.width;
}

#pragma mark - 计算距离现在多久
//计算时间 转换成 距离现在 多久
+ (NSString *)compareCurrentTime:(NSNumber *)date
{
    // 返回以1970/01/01 GMT为基准，然后过了secs秒的时间
    NSDate *compareDate = [NSDate dateWithTimeIntervalSince1970:[date doubleValue]];
    // 以当前时间(Now)为基准时间，返回实例保存的时间与当前时间(Now)的时间间隔
    NSTimeInterval  timeInterval = [compareDate timeIntervalSinceNow];
    timeInterval = -timeInterval;
    long temp = 0;
    NSString *result;
    if (timeInterval < 60) {
        result = [NSString stringWithFormat:@"刚刚"];
    }
    else if((temp = timeInterval / 60) < 60){
        result = [NSString stringWithFormat:@"%ld分钟前", temp];
    }
    
    else if((temp = temp / 60) < 24){
        result = [NSString stringWithFormat:@"%ld小时前", temp];
    }
    
    else if((temp = temp / 24) < 30){
        result = [NSString stringWithFormat:@"%ld天前", temp];
    }
    
    else if((temp = temp / 30) < 12){
        result = [NSString stringWithFormat:@"%ld月前", temp];
    }
    else{
        temp = temp / 12;
        result = [NSString stringWithFormat:@"%ld年前", temp];
    }
    
    return  result;
}
- (void)pathTapAction:(UITapGestureRecognizer *)tap
{
    if (![(UIImageView *)tap.view image]) {
        return;
    }
    //scrollView作为背景
    UIScrollView *bgView = [[UIScrollView alloc] init];
    bgView.frame = [UIScreen mainScreen].bounds;
    bgView.backgroundColor = [UIColor blackColor];
    bgView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapBg = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBgView:)];
    [bgView addGestureRecognizer:tapBg];
    
    UIImageView *picView = (UIImageView *)tap.view;
    
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.image = picView.image;
    imageView.frame = [bgView convertRect:picView.frame fromView:self];
    [bgView addSubview:imageView];
    
    [[[UIApplication sharedApplication] keyWindow] addSubview:bgView];
    
    self.lastImageView = imageView;
    self.originalFrame = imageView.frame;
    self.scrollView = bgView;
    //最大放大比例
    self.scrollView.maximumZoomScale = 1.5;
    self.scrollView.delegate = self;
    [UIView animateWithDuration:0.5 animations:^{
        CGRect frame = imageView.frame;
        frame.size.width = bgView.frame.size.width;
        frame.size.height = frame.size.width * (imageView.image.size.height / imageView.image.size.width);
        frame.origin.x = 0;
        frame.origin.y = (bgView.frame.size.height - frame.size.height) * 0.5;
        imageView.frame = frame;
        if (frame.size.height > HEIGHT) {
            _scrollView.contentSize = CGSizeMake(frame.size.width, frame.size.height);
            frame.origin.x = 0;
            frame.origin.y = 0;
            imageView.frame = frame;
        }
        
    }];
    
}

-(void)tapBgView:(UITapGestureRecognizer *)tapBgRecognizer
{
    self.scrollView.contentOffset = CGPointZero;
    [UIView animateWithDuration:0.5 animations:^{
        self.lastImageView.frame = self.originalFrame;
        tapBgRecognizer.view.backgroundColor = [UIColor clearColor];
    } completion:^(BOOL finished) {
        [tapBgRecognizer.view removeFromSuperview];
        self.scrollView = nil;
        self.lastImageView = nil;
    }];
}



//返回可缩放的视图
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return scrollView.subviews.firstObject;
}





/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/



@end
